import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TLetter } from 'src/entities/letter.entity';
import { getCurrentTime } from 'src/utils/index';
import { Response } from 'src/utils/response';
import {
  QueryResponse,
  QueryCurrentResponse,
  AddParam,
  AddResponse,
  UpdateParam,
  UpdateResponse,
  UpdateCurrentParam,
  UpdateCurrentResponse,
  DtlCurrentParam,
  DtlCurrentResponse,
  LetterDataInterface,
} from './letter.interface';

@Injectable()
export class LetterService {
  constructor(
    @InjectRepository(TLetter)
    private readonly repository: Repository<TLetter>,
  ) {}

  // 获取信件列表
  async queryLettersService(): QueryResponse {
    try {
      const result = await this.repository.find();
      return Response.success({ data: result });
    } catch (error) {
      return Response.error({ message: error.message });
    }
  }

  // 获取一封信页面显示的列表
  async queryCurrentLetterService(): QueryCurrentResponse {
    try {
      const result = await this.repository.find({
        where: {
          current: '1',
        },
      });
      const [letter] = result;
      return Response.success({ data: letter ?? {} });
    } catch (error) {
      return Response.error({ message: error.message });
    }
  }

  // 新增
  async addService(param: AddParam): AddResponse {
    const currentTime = getCurrentTime('YYYY-MM-DD HH:mm:ss');
    const letterInfo: LetterDataInterface = {
      ...param,
      current: '0',
      createdAt: currentTime,
      updatedAt: currentTime,
    };
    try {
      await this.repository.save(letterInfo);
      return Response.success({ message: '新增成功' });
    } catch (error) {
      return Response.error({ message: error.message });
    }
  }

  // 更新信件内容
  async updateService(param: UpdateParam): UpdateResponse {
    if (!param.id) {
      return Response.error({ message: '未传递id' });
    }
    const currentTime = getCurrentTime('YYYY-MM-DD HH:mm:ss');
    const letterInfo = {
      content: param.content,
      updatedAt: currentTime,
    };
    const result = await this.repository.update(param.id, letterInfo);
    if (result.affected !== 1) {
      return Response.error({ message: '更新失败' });
    }
    return Response.success({ message: '更新成功' });
  }

  // 将信件设置为一封信的内容
  async updateCurrentService(param: UpdateCurrentParam): UpdateCurrentResponse {
    if (!param.id) {
      return Response.error({ message: '未传递id' });
    }
    // 先将之前 current 为 1 的数据找出
    let letters = await this.repository.find({
      where: {
        current: '1',
      },
    });
    letters = letters.filter((v) => v.id);
    // 将这条数据更新为 0
    letters.forEach(async (item) => {
      await this.repository.update(item.id, { current: '0' });
    });
    const result = await this.repository.update(param.id, { current: '1' });
    if (result.affected !== 1) {
      return Response.error({ message: '设置失败' });
    } else {
      return Response.success({});
    }
  }

  // 删除
  async deleteService(param: DtlCurrentParam): DtlCurrentResponse {
    if (!param.id) {
      return Response.error({ message: '未传递id' });
    }
    try {
      await this.repository.delete(param.id);
      return Response.success({ message: '删除成功' });
    } catch (error) {
      return Response.error({ message: error.message });
    }
  }
}
